package com.example.cigarettepricesystem;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Picture;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Context context = MainActivity.this;
    private CigaretteAdapter cigaretteAdapter;
    private TextView tvHard;
    private TextView tvSoft;
    private TextView tvAddCig;
    private Button btnFindCig;
    private ListView lvMain;
    private EditText etFind;
    public DBManager dbHelper;
    private SQLiteDatabase db;
    private String sArgs;
    private String selection;//该字符串的作用：根据字符串sArg的值，更改需要搜索的字段
    //以下值的作用：储存数据表查询出来的数据，然后通过listview来显示
    private ArrayList<byte[]> cImg = new ArrayList<byte[]>();
    private ArrayList<String> cName = new ArrayList<String>();
    private ArrayList<String> cPrice = new ArrayList<String>();
    private String[] name;//作用未知
    //以下值的作用：被查询数据表所查询出来的数据所赋值，随后分别储存到数组cImg，cName，cPrice中
    private byte[] cimg;
    private String cname,cprice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbHelper = new DBManager(this);
        dbHelper.openDatabase();
        dbHelper.closeDatabase();
        init();
        btnFindCig.performClick();//应用打开时，默认点击一次"刷新"按钮，显示数据库所有数据
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        btnFindCig.performClick();//返回此页面时，重新点击一次刷新按钮
    }

    private void init() {
        tvHard = (TextView) findViewById(R.id.tv_hard);
        tvSoft = (TextView) findViewById(R.id.tv_soft);
        lvMain = (ListView) findViewById(R.id.lv_main);
        etFind = (EditText) findViewById(R.id.et_find);
        tvAddCig = (TextView) findViewById(R.id.tv_addCig);
        //点击添加按钮，跳转到添加香烟页面
        tvAddCig.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(context,AddCigActivity.class);
                startActivity(i);
            }
        });
        btnFindCig = (Button) findViewById(R.id.btn_findCig);
        tvHard.setOnClickListener(this);
        tvSoft.setOnClickListener(this);
        btnFindCig.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_hard:
                sArgs = "硬壳";
                break;
            case R.id.tv_soft:
                sArgs = "软壳";
                break;
            case R.id.btn_findCig:
                sArgs = etFind.getText().toString();
                break;
        }
        if (sArgs.equals("硬壳") || sArgs.equals("软壳")){
            selection = "cigaretteShell";
        }else {
            selection = "cigaretteName";
        }
        //每次点击时清空数组
        cImg.clear();
        cName.clear();
        cPrice.clear();
        show();
        cigaretteAdapter = new CigaretteAdapter();
        lvMain.setAdapter(cigaretteAdapter);
    }
    @SuppressLint("Range")
    private void show() {
        db = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/" + DBManager.DB_NAME, null);
        Cursor cursor = db.query("tb_cigarette",null,
                selection+" LIKE ?",new String[]{"%"+sArgs+"%"},
                null,null,"cigarettePrice");
        //根据查询记录的条数执行操作
        if (cursor.getCount() != 0){
            //将数据库查询出来的数据添加到ArrayList中
            while (cursor.moveToNext()){
                cimg = cursor.getBlob(cursor.getColumnIndex("cigaretteImg"));
                cname = cursor.getString(cursor.getColumnIndex("cigaretteName"));
                cprice = cursor.getString(cursor.getColumnIndex("cigarettePrice"));
                cImg.add(cimg);
                cName.add(cname);
                cPrice.add(cprice);
            }
        }else {
            cName.add("无");
            cPrice.add("无");
        }
        cursor.close();
        db.close();
        //将ArrayList转化为数组
        name = cName.toArray(new String[cName.size()]);
    }


    class CigaretteAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return name.length;
        }

        @Override
        public Object getItem(int position) {
            return name[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            ViewHolder holder = null;
            if (view == null){
                //调用布局，使其显示到listview上
                view = View.inflate(context,R.layout.cigratte_list,null);
                holder = new ViewHolder();
                holder.cName = (TextView) view.findViewById(R.id.tv_cigName);
                holder.cPrice = (TextView) view.findViewById(R.id.tv_cigPrice);
                holder.cImg = (ImageView)view.findViewById(R.id.img_cigImg);
                view.setTag(holder);
            }else {
                holder = (ViewHolder) view.getTag();
            }
            holder.cName.setText(cName.get(position));
            holder.cPrice.setText("价格: " + cPrice.get(position));
            if (cImg.isEmpty()){
                Drawable drawable = ContextCompat.getDrawable(context, R.drawable.noimg);
                holder.cImg.setImageDrawable(drawable);
            }else {
                //将byte[]数组里的数据转化为位图
                Bitmap bitmap =
                        BitmapFactory.decodeByteArray
                                (cImg.get(position), 0, cImg.get(position).length);
                holder.cImg.setImageBitmap(bitmap);
            }
            //设置listview点击事件
            lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(context,UpdatePriceActivity.class);
                    intent.putExtra("cname",cName.get(position));
                    intent.putExtra("cprice",cPrice.get(position));
                    startActivity(intent);
                }
            });
            return view;
        }
    }
    class ViewHolder{
        TextView cName,cPrice;
        ImageView cImg;
    }
}